//柯里化之前的函数add，调用需要4个参数： add(1, 2, 3, 4) 输出结果 10
function add(a, b, c, d) {
    return a + b + c + d;
}

/** 方案1 */
function curry1(fn, ...args){
    return fn.length <= args.length ? fn(...args)
    : curry1.bind(null, fn, ...args);
}

const curriedAdd1 = curry1(add);
console.log(curriedAdd1(1)(2)(3)(4));

/** 方案2 */
function curr2(fn){
    /** 参数列表为0或1时，不需要柯里化 */
    if (fn.length <=1)
        return fn;
    const generator = (...args) => {
        if (fn.length === args.length) {
            return fn(...args);
        }else {
            return (...args2) => {
                return generator(...args, ...args2);
            }
        }
    }
    return generator;
}

// 动态传入参数个数
function dynamicCarry(fn) {
    const args = [];

    function carried(...newArgs) {
        args.push(...newArgs);
        return carried;
    }

    carried.end = function(){
        return fn(...args);
    }

    return carried;
}

function sum(...args){
    return args.reduce((a,b) => a+b, 0);
}

const curriedSum = dynamicCarry(sum);

console.log(curriedSum(1)(2,3,4)(5).end());
